package com.gf.framwork.controller;

import com.alibaba.fastjson.JSON;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

@RestController
@RequestMapping("/")
@ConfigurationProperties(prefix = "publish")
public class HookController {

    private Map<String, String> comMap;

    public Map<String, String> getComMap() {
        return comMap;
    }

    public void setComMap(Map<String, String> comMap) {
        this.comMap = comMap;
    }

    @RequestMapping(value = "/mxhook",produces = "application/json;charset=UTF-8")
    public String mxDeploy(HttpServletRequest request, @RequestBody Map map) throws IOException {
        System.out.println(1);
        comMap.size();
        String key = request.getHeader("X-Gitee-Token");
        System.out.println("key = "+key);
        System.out.println("command："+comMap.get(key));
        System.out.println(JSON.toJSONString(comMap));
        if(!StringUtils.isEmpty(key) && comMap.containsKey(key)){
            exe(map,comMap.get(key));
        }else {
            return "非法访问";
        }
        return "returnString";
    }

    public void exe(Map map,String command){
        if(map.get("ref").toString().endsWith("master")){
            String returnString = "";
            Process pro = null;
            Runtime runTime = Runtime.getRuntime();
            if (runTime == null) {
                System.err.println("Create runtime false!");
            }
            try {
                pro = runTime.exec(command);
                BufferedReader input = new BufferedReader(new InputStreamReader(pro.getInputStream()));
                PrintWriter output = new PrintWriter(new OutputStreamWriter(pro.getOutputStream()));
                String line;
                while ((line = input.readLine()) != null) {
                    returnString = returnString + line + "\n";
                }
                input.close();
                output.close();
                pro.destroy();
                System.out.println("returnString:"+returnString);
            } catch (IOException ex) {
                Logger.getLogger(HookController.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

}
